package com.sevenit.nj.yrmtfish.common;

import java.io.InputStream;

import com.sevenit.nj.yrmtfish.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.widget.ImageView;

/**  
*  @description: 播放gif动画的类.
*  @version 1.0  
*  @author wangxw
*/  
public class GifView extends ImageView {

    private Movie mMovie = null;
    private long mMovieStart;

    /**
     * 构造函数.
     * @param context
     */
    public GifView(Context context) {
        super(context);
    }
    
    /**
     * 构造函数，这个必须实现，否则运行的时候会抛异常.
     * @param context
     * @param attrs
     */
    public GifView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        mMovie = null;  
        mMovieStart = 0;
        
        //从描述文件中读出gif的值，创建出Movie实例  .
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GifView);
        int srcID = a.getResourceId(R.styleable.GifView_src, 0);
        if(srcID>0){
        	InputStream is = context.getResources().openRawResource(srcID);  
        	mMovie = Movie.decodeStream(is);  
        }
        a.recycle();
    }
    
    /**
     * 构造函数.
     * @param context
     * @param attrs
     * @param defStyle
     */
    public GifView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    
    @Override 
    protected void onDraw(Canvas canvas) {
    	
    	if(mMovie == null){
    		return;
    	}
    	
        long now = android.os.SystemClock.uptimeMillis();
        
        if (mMovieStart == 0) {   // first time
            mMovieStart = now;
        }
        
        int dur = mMovie.duration();
        if (dur == 0) {
            dur = 1000;
        }
        int relTime = (int)((now - mMovieStart) % dur);
        mMovie.setTime(relTime);
        mMovie.draw(canvas, getWidth() - mMovie.width(),
                    getHeight() - mMovie.height());
        invalidate();
    }
}
